import { getInfoAPI, getUserInfoDetailAPI, loginAPI } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { resetRouter } from '@/router'

export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      // 存入cookie实现持久化
      setToken(token)
    },
    removeToken(state) {
      state.token = null
      // 移除cookie
      removeToken()
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    // 登录
    async actions_loginAPI(context, data) {
      const res = await loginAPI(data)
      console.log(res)
      context.commit('setToken', res)
    },
    // 获取用户信息
    async actions_getUserInfo(context) {
      // 获取用户信息
      const res = await getInfoAPI()
      const res2 = await getUserInfoDetailAPI(res.userId)
      context.commit('setUserInfo', { ...res, ...res2 })
      console.log(res)
      return res
    },
    // 退出登录
    actions_logout(context) {
      // 清除token
      context.commit('removeToken')
      // 清除用户资料
      context.commit('removeUserInfo')
      // 重置路由实例
      resetRouter()
      // 重置侧边栏菜单
      context.commit('permission/setRoutes', [], { root: true })
    }
  }
}
